package tij4.concurrent.exercise.ex23;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car {
    private boolean waxOn = false;
    public synchronized void waxed() {
        waxOn = true;
        notify();
    }
    public synchronized void buffed() {
        waxOn = false;
        notify();
    }
    public synchronized void waitForWaxing() throws InterruptedException{
//        while (waxOn == false)    //if和while都可以呀
        if(waxOn == false)
            wait();
    }
    public synchronized void waitForBuffing() throws InterruptedException{
//        while (waxOn == true)
        if (waxOn == true)
            wait();
    }
}

class WaxOn implements Runnable {
    private Car car;

    public WaxOn(Car car) {
        this.car = car;
        System.out.println("WaxOn   "  + car);
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
//            if(!Thread.interrupted()){
                System.out.println("Wax on!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.waxed();
                car.waitForBuffing();
            }
        }catch (InterruptedException e) {
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax On task");
    }
}

class WaxOff implements Runnable {
    private Car car;

    public WaxOff(Car car) {
        this.car = car;
        System.out.println("WaxOff   "  + car);
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
//            if (!Thread.interrupted()){
                car.waitForWaxing();
                System.out.println("Wax Off!");
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();
            }
        }catch (InterruptedException e) {
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax Off task");
    }

}

public class Ex23 {
    public static void main(String[] args) throws Exception{
        Car car = new Car();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new WaxOff(car));
        executorService.execute(new WaxOn(car));
        TimeUnit.SECONDS.sleep(5);
        executorService.shutdownNow();
    }
}
